import {Injectable} from '@angular/core';
import {Platform} from 'ionic-angular';
import {Media, MediaObject} from "@ionic-native/media";
import {File} from "@ionic-native/file";

@Injectable()
export class RecorderService {

    private recorder: MediaObject;
    private fileName: string;
    private iosDevice: boolean;
    private iosPath: string;

    constructor(private media: Media,
                private file: File,
                public platform: Platform) {
        this.iosDevice = this.platform.is('ios')
    }

    /**
     * begin record
     */
    startRecorder() {

        if (this.recorder) {
            this.recorder.release();
        }

        if (this.iosDevice) {
            // this.fileName = this.getNewGUIDString() + '.wav';
            this.fileName = this.getNewGUIDString() + '.m4a';
            this.file.createFile(this.file.tempDirectory, this.fileName, true).then(() => {
                this.iosPath = this.file.tempDirectory.replace(/^file:\/\//, '');
                this.recorder = this.media.create(this.iosPath + this.fileName);
                this.recorder.startRecord();
            });
        } else {
            // this.fileName = this.getNewGUIDString() + '.mp3';
            this.fileName = this.getNewGUIDString() + '.amr';
            this.recorder = this.media.create(this.fileName);
            this.recorder.startRecord();
        }
        //this.file.readAsBinaryString('',this.fileName);

    }

    /**
     * stop record
     * @returns {string}
     */
    stopRecorder(): string {

        if (!this.fileName || !this.recorder)
            return;

        this.recorder.stopRecord();

        if (this.iosDevice) {
            this.file.moveFile(
                this.file.tempDirectory,
                this.fileName,
                this.file.documentsDirectory,
                this.fileName);
        }
        return this.fileName;
    }

    /**
     * get file path
     * @param {string} fileName
     */
    getFilePath(fileName:string): string{
        let fileUri = '';

        if (this.platform.is('ios')) {
            fileUri = this.file.documentsDirectory.replace(/^file:\/\//, '')
                + fileName;
        } else {
            fileUri = this.file.externalRootDirectory + fileName;
        }
        return fileUri;
    }

    /**
     *
     * @returns {string}
     */
    getMimeType():string{
        if (this.iosDevice) {
            // return "audio/x-wav";
            return "audio/mp4a-latm";
        }
        else {
            // return "audio/mpeg";
            return "audio/amr";
        }
    }
    /**
     * start play record
     * @param {string} fname
     */
    /*startPlay(fname: string) {

        this.fileName = fname;

        if (this.recorder) {
            this.recorder.release();
        }
        const fileUri=this.getFilePath(this.fileName);
        this.recorder = this.media.create(fileUri);
        this.recorder.play();
    }*/

    /**
     * 开始播放--url
     */

    startPlay(url){
        if (this.recorder) {
            this.recorder.release();
        }
        this.recorder = this.media.create(url);
        this.recorder.play();
    }

    /**
     * pause record
     */
    pausePlay() {

        if (!this.recorder)
            return;

        this.recorder.pause();
    }

    /**
     * stop play record
     */
    stopPlay() {

        if (!this.recorder)
            return;

        this.recorder.stop();
    }

    /**
     * release record
     */
    releasePlay() {

        if (!this.recorder)
            return;
        this.recorder.release();
    }

    // 测试是否打开了录音权限
    test(){

    }

    /**
     * GUID Generator Funtion
     * @returns {string}
     */
    private getNewGUIDString() {
        let d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
            let r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
    }
    /**
     *
     * @param fileUrl
     */
    getPlatformFileUrl(fileUrl:string){
        if (this.iosDevice) {
            return fileUrl.replace(/^file:\/\//, '');
        }
        else{
            return fileUrl;
        }
    }

}
